package com.friend.chat.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine


/**
 * @des
 * @author batie fancy
 * @date 2022/6/22
 */
class PictureSelectorHelper {

    fun preView(list: ArrayList<LocalMedia>, context: Context) {
        PictureSelector.create(context)
            .openPreview()
            .setImageEngine(GlideEngine.createGlideEngine())
            .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                override fun onPreviewDelete(position: Int) {}
                override fun onLongPressDownload(context: Context?, media: LocalMedia?): Boolean {
                    return false
                }
            }).startActivityPreview(0, true, list)
    }

    fun takePhoto(context: Context, result: (compressPath: String) -> Unit) {
        PictureSelector.create(context)
            .openCamera(SelectMimeType.ofImage())
            .setCompressEngine(ImageFileCompressEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {

                    result?.get(0)?.compressPath?.let {
                        result(it)
                    }
                }

                override fun onCancel() {}
            })

    }

    fun takeVideo(context: Context, result: (compressPath: String) -> Unit) {
        PictureSelector.create(context)
            .openCamera(SelectMimeType.ofVideo())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    result?.get(0)?.compressPath?.let {
                        result(it)
                    }
                }

                override fun onCancel() {}
            })

    }


    fun takeAndSelectPhoto(
        context: Context,
        maxSelectNum: Int,
        result: (compressPath: String) -> Unit
    ) {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(maxSelectNum)
            .setCropEngine(ImageFileCropEngine())
            .setCompressEngine(ImageFileCompressEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {

                    result?.get(0)?.compressPath?.let {
                        result(it)
                    }
                }

                override fun onCancel() {}
            })
    }

    fun takeAndSelectPhoto1(
        context: Context,
        maxSelectNum: Int,
        result: (compressPath: String) -> Unit
    ) {
        PictureSelector.create(context)
            .openGallery(SelectMimeType.ofImage())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(maxSelectNum)

            .setCompressEngine(ImageFileCompressEngine())
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {

                    result?.get(0)?.compressPath?.let {
                        result(it)
                    }
                }

                override fun onCancel() {}
            })
    }


    /**
     * 自定义裁剪
     */
    private class ImageFileCropEngine : CropFileEngine {

        /**
         * 配制UCrop，可根据需求自我扩展
         *
         * @return
         */
        private fun buildOptions(): UCrop.Options {
            val options = UCrop.Options()
            options.setHideBottomControls(false)
            options.setFreeStyleCropEnabled(true)
            options.setShowCropFrame(true)
            options.setShowCropGrid(false)
            options.setCircleDimmedLayer(false)
            options.withAspectRatio(1f, 1f)
            //options.setCropOutputPathDir(getSandboxPath())
            options.isCropDragSmoothToCenter(false)
            /*   options.setSkipCropMimeType(getNotSupportCrop())
               options.isForbidCropGifWebp(cb_not_gif.isChecked())*/
            options.isForbidSkipMultipleCrop(true)
            options.setMaxScaleMultiplier(100f)
            /* if (selectorStyle != null && selectorStyle.selectMainStyle.statusBarColor != 0) {
                 val mainStyle = selectorStyle.selectMainStyle
                 val isDarkStatusBarBlack = mainStyle.isDarkStatusBarBlack
                 val statusBarColor = mainStyle.statusBarColor
                 options.isDarkStatusBarBlack(isDarkStatusBarBlack)
                 if (StyleUtils.checkStyleValidity(statusBarColor)) {
                     options.setStatusBarColor(statusBarColor)
                     options.setToolbarColor(statusBarColor)
                 } else {
                     options.setStatusBarColor(
                         ContextCompat.getColor(
                             getContext(),
                             R.color.ps_color_grey
                         )
                     )
                     options.setToolbarColor(
                         ContextCompat.getColor(
                             getContext(),
                             R.color.ps_color_grey
                         )
                     )
                 }
                 val titleBarStyle = selectorStyle.titleBarStyle
                 if (StyleUtils.checkStyleValidity(titleBarStyle.titleTextColor)) {
                     options.setToolbarWidgetColor(titleBarStyle.titleTextColor)
                 } else {
                     options.setToolbarWidgetColor(
                         ContextCompat.getColor(
                             getContext(),
                             R.color.ps_color_white
                         )
                     )
                 }
             } else {
                 options.setStatusBarColor(
                     ContextCompat.getColor(
                         getContext(),
                         R.color.ps_color_grey
                     )
                 )
                 options.setToolbarColor(ContextCompat.getColor(getContext(), R.color.ps_color_grey))
                 options.setToolbarWidgetColor(
                     ContextCompat.getColor(
                         getContext(),
                         R.color.ps_color_white
                     )
                 )
             }*/
            return options
        }


        override fun onStartCrop(
            fragment: Fragment,
            srcUri: Uri?,
            destinationUri: Uri?,
            dataSource: ArrayList<String?>?,
            requestCode: Int
        ) {
            val options: UCrop.Options = buildOptions()
            val uCrop = UCrop.of(srcUri!!, destinationUri!!, dataSource)
            uCrop.withOptions(options)
            uCrop.setImageEngine(object : UCropImageEngine {
                override fun loadImage(context: Context, url: String, imageView: ImageView) {
                    /* if (!ImageLoaderUtils.assertValidRequest(context)) {
                         return
                     }*/
                    Glide.with(context).load(url).override(180, 180).into(imageView)
                }

                override fun loadImage(
                    context: Context,
                    url: Uri,
                    maxWidth: Int,
                    maxHeight: Int,
                    call: UCropImageEngine.OnCallbackListener<Bitmap>
                ) {
                    Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight)
                        .into(object : CustomTarget<Bitmap>() {
                            override fun onResourceReady(
                                resource: Bitmap,
                                @Nullable transition: Transition<in Bitmap>?
                            ) {
                                if (call != null) {
                                    call.onCall(resource)
                                }
                            }

                            override fun onLoadCleared(@Nullable placeholder: Drawable?) {
                                if (call != null) {
                                    call.onCall(null)
                                }
                            }
                        })
                }
            })
            uCrop.start(fragment.requireActivity(), fragment, requestCode)
        }
    }
}